<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="625px" :before-close="handleClose" custom-class="dialog">
    <el-form ref="form" :model="formInfo" :rules="rules" label-width="140px" label-position="right">
      <el-form-item v-if="versionAddOrEdit === 'add' && activeName !== 'IOS'" label="应用包" prop="package">
        <el-upload
          class="upload-demo"
          action="ota/v1/app/version/info/upload/version/file"
          :headers="headers"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :data="{ appInfoId }"
          multiple
          :accept="uploadFileType">
          <el-button v-if="!uploadSuccessedFile" size="small" icon="el-icon-plus" class="upload-btn">上传{{ uploadFileType }}文件</el-button>
          <el-input v-else v-model="formInfo.fileName" class="file-name">{{ formInfo.fileName }}</el-input>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="activeName !== 'IOS'" label="版本号">
        {{ formInfo.versionCode || '-' }}
      </el-form-item>
      <el-form-item v-if="activeName !== 'IOS'" label="包体大小" prop="AndroidName">
        {{ formInfo.packageSize / 1024 /1024 || '-' }}
      </el-form-item>
      <el-form-item v-if="activeName !== 'IOS'" label="MD5值" prop="iosName">
        {{ formInfo.md5 || '-' }}
      </el-form-item>
      <el-form-item v-if="activeName === 'IOS'" label="版本号" prop="version">
        <el-input
          v-model="formInfo.versionCode"
          placeholder="请输入版本号"></el-input>
      </el-form-item>
      <el-form-item label="提示频率" prop="frequency">
        <el-radio-group v-model="formInfo.frequency">
          <el-radio :label="0">每天</el-radio>
          <el-radio :label="1">每次</el-radio>
          <el-radio :label="2">每三天</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="更新日志" prop="description">
        <el-input
          v-model="formInfo.description"
          type="textarea"
          maxlength="200"
          show-word-limit
          placeholder="请输入更新日志"
          :rows="4"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="14" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="14" @click="onSubmit">确 定
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addVersion, updateVersion } from '@/api/app/myapp'
import store from '@/store'
export default {
  name: 'versionDialog',
  props: {
    applyData: {
      type: Object,
      default: () => { return {} }
    },
    activeName: {
      type: String,
      default: 'uni-app'
    },
    versionAddOrEdit: {
      type: String,
      default: 'add'
    },
    versionRow: {
      type: Object,
      default: () => { return {} }
    }
  },
  data() {
    const validatePackage = (rule, value, callback) => {
      if (this.fileList.length === 0) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    }
    return {
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      dialogVisible: false,
      appInfoId: '', // app_info表id
      formInfo: {
        versionCode: "", // 版本号
        frequency: '', // 提示频率（0：每天，1：每次，2：每三天）
        packageSize: 0, 	// 包体大小
        md5: "", // md5值
        fileName: "", // 上传App应用文件名称
        description: "", // 更新说明
        url: "", // 	包地址
        appVersionInfoId: '' // app版本信息id
      },
      uploadSuccessedFile: false,
      fileList: [], // 上传的固件文件
      uploadSuccessOrError: false, // 上传固件成功则展示固件基本信息否则不展示
      rules: {
        package: { required: true, validator: validatePackage, trigger: 'blur' },
        frequency: [
          { required: true, message: '请选择提示频率', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入更新日志', trigger: 'blur' }
        ],
        versionCode: [
          { required: true, message: '请输入版本号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.versionAddOrEdit === 'add' ? `创建${this.activeName}版本` : `编辑${this.activeName}版本`
    },
    uploadFileType() {
      return this.activeName === 'uni-app' ? 'wgt' : 'apk'
    },
    versionType() {
      const tabText = {
        'uni-app': '0',
        'Android': '1',
        'IOS': '2'
      }
      return tabText[this.activeName] || ''
    }
  },
  watch: {
    // app应用有值得时候
    applyData(newVal, oldVal) {
      this.appInfoId = newVal.appInfoId
    },
    // 编辑带过来的单条数据
    versionRow(newVal, oldVal) {
      this.formInfo = {
        versionCode: newVal.versionCode,
        frequency: newVal.frequency,
        packageSize: newVal.packageSize,
        md5: newVal.md5,
        fileName: newVal.fileName,
        description: newVal.description,
        appVersionInfoId: newVal.appVersionInfoId
      }
    }
  },
  methods: {
    validateApplyName(rule, value, callback) {
      const flag = new RegExp(/^[\u4E00-\u9FFFa-zA-Z\p{P}]+$/u).test(value)
      if (!flag) {
        callback(new Error('请使用规范名称'))
      } else {
        callback()
      }
    },
    // 上传之前做校验
    beforeUpload(file) {
      // 在上传之前检查文件类型
      const extension = file.name.split('.').pop() // 获取上传文件的扩展名
      const allowedExtensions = this.uploadFileType

      if (!allowedExtensions.includes(extension)) {
        this.$message.error(`只允许上传 ${this.uploadFileType} 文件`)
        return false // 阻止文件上传
      }

      return true // 允许文件上传
    },
    // 文件上传成功
    uploadSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.fileList = file
        this.formInfo.versionCode = res.data.versionCode
        this.formInfo.md5 = res.data.md5
        this.formInfo.packageSize = res.data.packageSize
        this.formInfo.url = res.data.url
        this.formInfo.fileName = res.data.fileName
        this.uploadSuccessedFile = true
      } else {
        this.$message.error(res.msg)
      }
    },
    // 文件上传失败
    uploadError(err, file, fileList) {
      this.$message.error(err)
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.uploadSuccessOrError = false
      Object.keys(this.formInfo).forEach(key => {
        this.formInfo[key] = ""
      })
      this.$refs['form'].resetFields()
    },
    // 新增/编辑版本
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = {
            ...this.formInfo,
            type: this.versionType,
            appInfoId: this.appInfoId
          }
          const request = this.versionAddOrEdit === 'add' ? addVersion : updateVersion
          request(params).then(res => {
            this.$message.success(`${this.versionAddOrEdit === 'add' ? '新增' : '编辑'}${this.activeName}版本成功`)
            this.$parent.$refs.tableList.queryVersionList()
          }).catch(err => {
            this.$message.error(err.message)
          }).finally(() => {
            Object.keys(this.formInfo).forEach(key => {
              this.formInfo[key] = ""
            })
            this.uploadSuccessedFile = false
            this.$refs['form'].resetFields()
            this.dialogVisible = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .upload-demo {
  .el-upload {
    width: 100%;
  }
  .upload-btn,
  .file-name {
    width: 100%;
    color: #275FE8;
    font-size: 14px;
    height: 32px;

    ::v-deep .el-input__inner {
      color: #275FE8;
    }
  }

  .el-upload-list {
    display: none;
  }

  .el-button {
    width: 100%;
    color: #275fe8;
    font-size: 14px;
  }
}
</style>
